package xin.nick.common.core.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.http.MediaType;
import xin.nick.common.core.entity.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

public class ResultUtil {

    /**
     * 组装response返回Result
     *
     * @param response HttpServletResponse
     * @param result   Result
     * @throws IOException IOException
     */
    public static void responseResult(HttpServletResponse response, Result<?> result) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println(JSON.toJSONString(result));
        writer.flush();
    }


    /**
     * 转换Page对象
     *
     * @param page        Page<T>
     * @param targetClass Class<T>
     * @return Page<T>
     */
    public static <T> Page<T> convertPage(Page<?> page, Class<T> targetClass) {
        return convertPage(page, targetClass, null);
    }


    /**
     * 转换Page对象
     *
     * @param page        Page<?
     * @param targetClass Class<T>
     * @param copyOptions CopyOptions
     * @return Page<T>
     */
    public static <T> Page<T> convertPage(Page<?> page, Class<T> targetClass, CopyOptions copyOptions) {
        Page<T> resultPage = new Page<>();
        BeanUtil.copyProperties(page, resultPage, "records");

        List<?> records = page.getRecords();
        if (Objects.nonNull(copyOptions)) {
            resultPage.setRecords(BeanUtil.copyToList(records, targetClass, copyOptions));
        } else {
            resultPage.setRecords(BeanUtil.copyToList(records, targetClass));
        }
        return resultPage;
    }

}
